<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, shallowRef, computed, ref } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { ElMessage } from 'element-plus'

import { appConfig } from '@/config'

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const props = defineProps({
  modeValue: String,
  editorConfig: {
    default: () => ({
      placeholder: '请输入内容...',
      MENU_CONF: {}
    }),
    type: Object
  },
  toolbarConfig: {
    type: Object,
    default: () => ({})
  },
  height: {
    type: Number,
    default: 400
  },
  name: {
    type: String,
    default: 'files'
  },
  http: Function
})

const config = ref(props.editorConfig)
const loading = ref(false)

const emits = defineEmits({
  'update:modelValue': (data) => data
})

// 内容 HTML
const value = computed({
  get() {
    return props.modeValue
  },
  set(val) {
    emits('update:modelValue', val)
  }
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  // eslint-disable-next-line eqeqeq
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor: any) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}

// 图片上传设置
config.value.MENU_CONF['uploadImage'] = {
  // 服务端地址
  maxNumberOfFiles: 1,
  allowedFileTypes: ['image/*'],
  async customUpload(file: any, insertFn: (data: any) => void) {
    if (!(props.http && typeof props.http === 'function'))
      return ElMessage({ type: 'warning', message: 'http不能为空' })
    if (!file.type.includes('image')) {
      return ElMessage({
        type: 'error',
        message: '请上传图片格式的文件'
      })
    }
    if (file.size / 1024 / 1024 > 200) {
      return ElMessage({
        type: 'error',
        message: '请上传200M以内的图片！'
      })
    }
    const formData = new FormData()
    formData.append(props.name, file)
    loading.value = true
    props
      .http(formData)
      .then((res: any) => {
        loading.value = false
        insertFn(appConfig.baseFilesUrl + res.data.imgId)
      })
      .catch(() => {
        loading.value = false
      })
  }
}
</script>

<template>
  <div style="border: 1px solid #ccc; z-index: 1001">
    <!-- 工具栏 -->
    <Toolbar
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      style="border-bottom: 1px solid #ccc"
    />
    <!-- 编辑器 -->
    <Editor
      v-model="value"
      :defaultConfig="editorConfig"
      :style="{ height: height + 'px', overflowY: 'hidden' }"
      @onCreated="handleCreated"
    />
  </div>
</template>

<!-- 别忘了引入样式 -->
<style src="@wangeditor/editor/dist/css/style.css"></style>
